using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;

namespace cb0tServer
{
    class RoomLocationFinder
    {
        private Thread thread;

        public void Query()
        {
            this.thread = new Thread(new ThreadStart(this.Work));
            this.thread.Start();
        }

        private void Work()
        {
            try
            {
                HttpWebRequest r = (HttpWebRequest)WebRequest.Create("http://www.melissadata.com/lookups/iplocation.asp?ipaddress=" +
                    Uri.EscapeDataString(CoreSettings.room_external_ip.ToString()));
                r.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; Media Center PC 5.0)";
                StreamReader s = new StreamReader(r.GetResponse().GetResponseStream(), Encoding.UTF8);
                String html = s.ReadToEnd();
                s.Close();

                CoreSettings.room_location = this.Parse(html);
            }
            catch { }
        }

        private String Parse(String html)
        {
            List<String> lines = new List<String>(html.Split(new String[] { "\r\n" }, StringSplitOptions.None));
            List<String> results = new List<String>();

            foreach (String line in lines)
            {
                String eval = line.TrimStart();

                if (eval.IndexOf("<tr><td align=\"right\">State or Region</td>") > -1)
                {
                    eval = eval.Substring(22 + 20);
                    eval = removeEntities(removeHtml(eval)).Trim();
                    eval = formatResult(eval);

                    if (eval != "-")
                        results.Add(eval);
                }

                if (eval.IndexOf("<tr><td align=\"right\">Country</td>") > -1)
                {
                    eval = eval.Substring(22 + 12);
                    eval = removeEntities(removeHtml(eval)).Trim();
                    eval = formatResult(eval);

                    if (eval != "-")
                        results.Add(eval);
                }
            }

            return results.Count > 0 ? String.Join(", ", results.ToArray()) : "Unknown.";
        }

        private String formatResult(String str)
        {
            List<String> tmp1 = new List<String>(str.Split(new String[] { " " }, StringSplitOptions.None));
            List<String> tmp2 = new List<String>();

            foreach (String tmp3 in tmp1)
            {
                if (tmp3.Length > 0)
                {
                    String tmp4 = tmp3.Substring(0, 1).ToUpper() + tmp3.Substring(1).ToLower();
                    tmp2.Add(tmp4);
                }
                else
                {
                    tmp2.Add(tmp3);
                }
            }

            return String.Join(" ", tmp2.ToArray());
        }



        private String removeEntities(String str)
        {
            String _str = str;
            _str = _str.Replace("&quot;", "\"");
            _str = _str.Replace("&amp;", "&");
            _str = _str.Replace("&#160;", " ");
            _str = _str.Replace("&lt;", "<");
            _str = _str.Replace("&gt;", ">");
            _str = _str.Replace("&nbsp;", "");
            return _str;
        }

        private String removeHtml(String unfiltered)
        {
            String result = unfiltered;

            while (((result.IndexOf("<") > -1)
                && (result.IndexOf(">") > -1))
                && (result.IndexOf("<") < result.IndexOf(">")))
            {
                result = result.Substring(0, result.IndexOf("<"))
                    + result.Substring(result.IndexOf(">") + 1);
            }

            return result;
        }

    }
}
